package com.atguigu.gulimall.product.service.impl;

import com.atguigu.gulimall.product.entity.CategoryBrandRelationEntity;
import com.atguigu.gulimall.product.service.CategoryBrandRelationService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.product.dao.BrandDao;
import com.atguigu.gulimall.product.entity.BrandEntity;
import com.atguigu.gulimall.product.service.BrandService;
import org.springframework.transaction.annotation.Transactional;


@Transactional
@Service("brandService")
public class BrandServiceImpl extends ServiceImpl<BrandDao, BrandEntity> implements BrandService {
    @Autowired
    private CategoryBrandRelationService categoryBrandRelationService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        String key = (String) params.get("key");
        LambdaQueryWrapper<BrandEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(StringUtils.isNotEmpty(key),BrandEntity::getBrandId,key).
        or().like(StringUtils.isNotEmpty(key),BrandEntity::getName,key);
        IPage<BrandEntity> page = this.page(
                new Query<BrandEntity>().getPage(params),
                queryWrapper
        );

        return new PageUtils(page);
    }

    @Override
    public void updateCascade(BrandEntity brand) {
        //修改brand表
        this.updateById(brand);
        //修改关联表
        if(StringUtils.isNotBlank(brand.getName())){
            UpdateWrapper<CategoryBrandRelationEntity> updateWrapper= new UpdateWrapper<>();
            updateWrapper.eq("brand_id",brand.getBrandId())
                    .set("brand_name",brand.getName());
            categoryBrandRelationService.update(updateWrapper);
        }
    }

    @Override
    public List<BrandEntity> getBrandList(Long catId) {
        List<CategoryBrandRelationEntity> list = categoryBrandRelationService.list(new QueryWrapper<CategoryBrandRelationEntity>().eq("catelog_id", catId));
        List<BrandEntity> brandEntities =
        list.stream().map(item->{
            BrandEntity brandEntity = new BrandEntity();
            brandEntity.setBrandId(item.getBrandId());
            brandEntity.setName(item.getBrandName());
            return brandEntity;
        }).collect(Collectors.toList());
        return brandEntities;
    }

}